package algorithm.leetcode

import java.lang.IllegalArgumentException
import java.lang.StringBuilder
import kotlin.random.Random

class twosum {

    fun twoSum(ar : IntArray, target : Int) : IntArray?{
        val indexes = ar.indices
        indexes.forEach {
            val i = it
            val inner = indexes.filter { j -> j > i }
            inner.forEach{j ->
                if (ar[i] + ar[j] == target)
                    return intArrayOf(i, j)
            }
        }
        return null;
    }

    fun twoSumHash(ar : IntArray, target : Int) : IntArray?{
        val repo = hashMapOf<Int, Int>()
        ar.indices.forEach {
            repo[ar[it]] = it
        }
        ar.indices.forEach {
            val d = target - ar[it]
            if(repo.containsKey(d) && repo[d] != it){
                return intArrayOf(repo[d]!!, it)
            }
        }
        throw IllegalArgumentException("no result found")
    }
}

fun main(args: Array<String>) {
    val t = twosum()
    val startTime = System.currentTimeMillis()
    var res = t.twoSumHash(intArrayOf(1,2,3,4,5,6), 7)
    val endTime = System.currentTimeMillis()
    res?.forEach(::println)
    println("use time = ${endTime - startTime}ms")

    val map = hashMapOf<String, Bean>()
    map.put("s1", Bean("s1"))
    map.put("s2", Bean("s1"))
    println("s1 ${ if (map["s1"]?.equals(map["s2"]) == true) "==" else "!=" } s2 s1 hascode = ${map["s1"].hashCode()} s2 hascode = ${map["s2"].hashCode()}")
}

fun Random.nextString() : String{
    val sb = StringBuilder()
    for(i in IntRange(0, 10)){
        sb.append((nextInt(26) + 97).toChar())
    }
    return sb.toString()
}

data class Bean(val s1 : String = "str", val s2 : String = Random.nextString()){

    override fun equals(other: Any?): Boolean {
        if(other == null) return false

        if(other is Bean){
            if(other.s1.equals(s1))
                return true
        }
        return false
    }

    override fun hashCode(): Int {
        return (s1 + s2).hashCode()
    }
}